<template>
  <div class="cart">
    <div class="cart-top">
      <p class="cart-title">购物车</p>
      <div class="seller-commit">
        <div class="commitbox">
          <p class="circle"></p>
          <p class="commit">30天无忧退货</p>
        </div>
        <div class="commitbox">
          <p class="circle"></p>
          <p class="commit">48小时快速退款</p>
        </div>
        <div class="commitbox">
          <p class="circle"></p>
          <p class="commit">满88元免邮费</p>
        </div>
      </div>
    </div>

    <div class="cart-content">
      <div class="cart-box" v-for="item in info" :key="item.id">
        <div class="checkbox">
          <van-checkbox class="box" v-model="item.checked"></van-checkbox>
        </div>
        <img :src="item.list_pic_url" alt="" />
        <div class="info">
          <p class="name">{{ item.goods_name }}</p>
          <div class="extra-info">
            <p class="price">¥{{ item.retail_price }}</p>
            <van-stepper v-model="item.number" />
          </div>
        </div>
      </div>
    </div>

    <div class="cart-bottom">
        <van-checkbox v-model="isAllSelect">全选</van-checkbox>
        <div class="bottom-right"> 
          <div class="price">合计:<span>¥{{ price }}</span></div>
          <div class="submit" @click="onSubmit">下单</div>
        </div>
    </div>
      
  </div>
</template>

<script>
import {
cartList,
submitAction 
} from "@/api/cart/index";
export default {
  name: "Index",

  data() {
    return {
      info: [],
      checked:true,
    };
  },

  created() {
    cartList({
      openId: localStorage.getItem("openId"),
    }).then((res) => {
      console.log(res);
      res.data.forEach(ele => {
        ele.checked = false
      })
      this.info = res.data;
      
    });
  },

  computed:{
    price(){
        return this.info.reduce((total,current)=>{
            if(current.checked){
                return total + current.number*current.retail_price
            }else{
                return total
            }
        },0)
    },
    isAllSelect:{
        get(){
            if(this.info.length == 0){
                return false
            }
            return this.info.every(el => el.checked)
        },
        set(val){
            this.info.forEach(el =>{
                el.checked = val
            })
        }
    }
  },

  mounted() {},

  methods: {
    onSubmit(){
        if(!this.price){
          return
        }
        submitAction({
            allPrise:this.price,
            goodsId:this.info.filter(ele=>ele.checked).map(ele => ele.goods_id).join(","),
            openId:localStorage.getItem('openId')
        })
        .then(res=>{
            console.log(res);
            this.$router.push("/cart/order")
        })
    }
  },

};
</script>

<style scoped lang="scss">
@import "scss/index.scss";
* {
  margin: 0px;
  padding: 0px;
}
</style>